﻿using System;
using System.Collections.Generic;

namespace Handin1
{
    public class PricePortal : IFindItem
    {
        private readonly IItemCache _cache;
        private readonly ISearchSubSupplier _subSupplier;
        private DateTime _expire = DateTime.Now;

        public PricePortal(IItemCache cache, ISearchSubSupplier subSupplier)
        {
            _cache = cache;
            _subSupplier = subSupplier;
        }

        #region IFindItem Members

        public List<IItem> LookUpItem(ulong partnumber, string description)
        {
            List<IItem> result = _cache.LookUpItem(partnumber, description);
            _cache.RemoveItems(GetExpiredItems(result)); // remove expired items

            result = _cache.LookUpItem(partnumber, description); // update results

            if (result.Count > 0)
                return result;

            if ((result = _subSupplier.LookUpItem(partnumber, description)).Count > 0)
                _cache.AddItems(result);
            return result;
        }

        public void SetCacheExpireTime(uint hours)
        {
            _expire = DateTime.Now.AddHours(hours);
        }

        #endregion

        private List<IItem> GetExpiredItems(List<IItem> list)
        {
            var expiredItems = new List<IItem>();
            foreach (IItem item in list)
            {
                if (DateTime.Compare(item.Hit, _expire) > 0)
                    expiredItems.Add(item);
            }
            return expiredItems;
        }

        private static int Main()
        {
            return 0;
        }
    }
}